import {io} from 'socket.io-client'
import {useEffect} from 'react'
import {atom} from 'jotai'
import {useAtom} from 'jotai'

export const socket = io('http://localhost:3000')

export const charactersAtom = atom([])
export const mapAtom = atom(null)
export const userAtom = atom(null)
export const itemsAtom = atom(null)


export const SocketManager = () => {

  const [characters, setCharacters] = useAtom(charactersAtom)
  const [map, setMap] = useAtom(mapAtom)
  const [user, setUser] = useAtom(userAtom)
  const [items, setItems] = useAtom(itemsAtom)

  const onConnect = () => {
    console.log('connect')
  }

  const onDisConnect = () => {
    console.log('disconnect')
  }

  const onHello = (_value) => {
    console.log('hello', _value)
    setMap(_value.map)
    setUser(_value.id)
    setCharacters(_value.characters)
    setItems(_value.items)
  }

  const onMapUpdate = (_value) => {
    console.log('map-update', _value)
    setMap(_value.map)
    setCharacters(_value.characters)
  }

  const onCharacters = (_characters) => {
    console.log('characters', _characters)
    setCharacters(_characters)
  }

  // const onPlayerMove = (_character) => {
  //   console.log('character', _character)
  //   setCharacters((old_characters) => {
  //     return old_characters.map(oc => {
  //       if (oc.id === _character.id) {
  //         return _character
  //       }
  //       return oc
  //     })
  //   })
  // }

  useEffect(() => {
    socket.on('connect', onConnect)
    socket.on('disconnect', onDisConnect)
    socket.on('hello', onHello)
    socket.on('characters', onCharacters)
    // socket.on('player-move', onPlayerMove)
    socket.on('map-update', onMapUpdate)

    return () => {
      socket.off('connect', onConnect)
      socket.off('disconnect', onDisConnect)
      socket.off('hello', onHello)
      socket.off('characters', onCharacters)
      // socket.off('player-move', onPlayerMove)
      socket.off('map-update', onMapUpdate)
    }
  }, [])
}


